﻿using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using DNBProject.Common;
using DNBProject.Common.PopupInfo;
using DNBProject.DAO;
using DNBProject.Model;
using DNBProject.Model.Map;
using DNBProject.Model.PopupPartial;
using DNBProject.Model.ReportPartial;
using DNBProject.ViewModel;
using System.Linq;

namespace DNBProject.Controllers.Map
{
    public class MapController : Controller
    {
        #region Controller

        /// <summary>
        /// Redirect TopMap Screen
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //get table tbKKXQ
            var modelietbKkxq = (IEnumerable<tbKKXQ>) DaoBase.Data.tbKKXQs;
            ViewBag.tbKKXQ = modelietbKkxq;
            var modelietbNuocsong = (IEnumerable<tbNuocsong>) DaoBase.Data.tbNuocsongs;
            ViewBag.tbNuocsong = modelietbNuocsong;
            var modelietbNuocho = (IEnumerable<tbNuocho>) DaoBase.Data.tbNuochoes;
            ViewBag.tbNuocho = modelietbNuocho;
            var modeltbNuocngam = (IEnumerable<tbNuocngam>) DaoBase.Data.tbNuocngams;
            ViewBag.tbNuocngam = modeltbNuocngam;
            var modeltbNuocbien = (IEnumerable<tbNuocbien>) DaoBase.Data.tbNuocbiens;
            ViewBag.tbNuocbien = modeltbNuocbien;
            var modeltbMothuysan = (IEnumerable<tbMothuysan>) DaoBase.Data.tbMothuysans;
            ViewBag.tbMothuysan = modeltbMothuysan;
            var modeltbTramtich = (IEnumerable<tbTramtich>) DaoBase.Data.tbTramtiches;
            ViewBag.tbTramtich = modeltbTramtich;
            var modeltbDat = (IEnumerable<tbDat>) DaoBase.Data.tbDats;
            ViewBag.tbDat = modeltbDat;
            var modeltbCssxKhongKhi = (IEnumerable<tbCSSX_KhongKhi>) DaoBase.Data.tbCSSX_KhongKhi;
            ViewBag.tbCSSX_KhongKhi = modeltbCssxKhongKhi;
            var modeltbCssxNuocthai = (IEnumerable<tbCSSX_Nuocthai>) DaoBase.Data.tbCSSX_Nuocthai;
            ViewBag.tbCSSX_Nuocthai = modeltbCssxNuocthai;

            //Get data
            var model = CreateViewModel();

            //Set the server path image url for each layer
            foreach (var config in model.LayerConfig)
            {
                config.ImageUrl = Url.Content(config.ImageUrl);
                config.TocImageUrl = Url.Content(config.TocImageUrl);
            }

            //Redirect to map top
            return View(model);
        }

        /// <summary>
        /// Get data for poup
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mappedTable"></param>
        /// <returns></returns>
        public ActionResult GetDataPopup(int? id, string mappedTable)
        {
            var result = GetModel(id, mappedTable);
            return PartialView("PopupPartial/EntirePopupPartial", result);
        }

        /// <summary>
        /// Excute the reload data action on draging comlete
        /// </summary>
        /// <param name="bound"></param>
        /// <returns></returns>
        public ActionResult ReloadDataOnEndDrag(BoundMapModel bound)
        {
            return null;
        }

        /// <summary>
        /// Get data for static table
        /// </summary>
        /// <returns></returns>
        public ActionResult GetStaticTable(StaticCriteriaModel dataModel)
        {
            return null;
        }
        #endregion

        #region Method

        /// <summary>
        /// Update the coordinate data to the geographic reference for view model
        /// </summary>
        private void UpdateViewModelLonLat()
        {
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbKKXQs);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbDats);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbNuocbiens);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbNuochoes);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbNuocngams);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbNuocsongs);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbTramtiches);
            CommonInfo.UpdateDataLonLat(DaoBase.Data.tbMothuysans);
        }

        /// <summary>
        /// Create view model
        /// </summary>
        /// <returns></returns>
        private MapTopViewModel CreateViewModel()
        {
            //Get data for view model
            var model = new MapTopViewModel
                {
                    LayerConfig = CommonInfo.LayerConfig,
                    Kkxq = (from p in DaoBase.Data.tbKKXQs
                            select new FeatureDataModel
                                {
                                    Id = p.ID,
                                    MappedTable = "tbKkxq",
                                    Lon = p.colLon,
                                    Lat = p.colLat
                                }).ToList(),

                    Nuocbien = (from p in DaoBase.Data.tbNuocbiens
                                select new FeatureDataModel
                                    {
                                        Id = p.ID,
                                        MappedTable = "tbNuocbien",
                                        Lon = p.colLon,
                                        Lat = p.colLat
                                    }).ToList(),

                    Dat = (from p in DaoBase.Data.tbDats
                           select new FeatureDataModel
                               {
                                   Id = p.ID,
                                   MappedTable = "tbDat",
                                   Lon = p.colLon,
                                   Lat = p.colLat
                               }).ToList(),

                    Nuocho = (from p in DaoBase.Data.tbNuochoes
                              select new FeatureDataModel
                                  {
                                      Id = p.ID,
                                      MappedTable = "tbNuocho",
                                      Lon = p.colLon,
                                      Lat = p.colLat
                                  }).ToList(),

                    Nuocsong = (from p in DaoBase.Data.tbNuocsongs
                                select new FeatureDataModel
                                    {
                                        Id = p.ID,
                                        MappedTable = "tbNuocsong",
                                        Lon = p.colLon,
                                        Lat = p.colLat
                                    }).ToList(),

                    Nuocngam = (from p in DaoBase.Data.tbNuocngams
                                select new FeatureDataModel
                                    {
                                        Id = p.ID,
                                        MappedTable = "tbNuocngam",
                                        Lon = p.colLon,
                                        Lat = p.colLat
                                    }).ToList(),

                    TramTich = (from p in DaoBase.Data.tbTramtiches
                                select new FeatureDataModel
                                    {
                                        Id = p.ID,
                                        MappedTable = "tbTramtich",
                                        Lon = p.colLon,
                                        Lat = p.colLat
                                    }).ToList(),

                    MoThuySan = (from p in DaoBase.Data.tbMothuysans
                                 select new FeatureDataModel()
                                     {
                                         Id = p.ID,
                                         MappedTable = "tbMothuysan",
                                         Lon = p.colLon,
                                         Lat = p.colLat
                                     }).ToList(),
                    
                    ReportModel = new ReportModel()
                        {
                            TieuChuan = (from p in DaoBase.Data.tbTieuChuanCots
                                 select new SelectionItemModel()
                                     {
                                         Id = p.ID,
                                         Name = p.tbTieuChuan.colTen + " " + p.colTen
                                     }).ToList()
                        }
                };

            //Get data sample from tbKKXQ_Mau
            model.ReportModel.Samples = (from p in DaoBase.Data.tbKKXQ_Mau
                                         select p).ToList().Select(p => new MeasureSampleModel()
                                         {
                                             Id = p.ID,
                                             BeginTime = p.colTgBD,
                                             FinishTime = p.colTgKT,
                                             Reason = p.colLydo,
                                             Note = p.colGhichu,
                                             Name = p.colNgay == null ? "" : p.colNgay.Value.ToString("MM/yyyy")
                                         }).ToList();

            model.ReportModel.Areas = (from p in DaoBase.Data.tbKKXQ_Mau_KQ
                                       group p.tbKKXQ_Mau by new { Id = p.tbKKXQ.ID, 
                                                                   Kyhieu = p.tbKKXQ.colKyhieu, 
                                                                   Vitri = p.tbKKXQ.colVitri, 
                                                                   Lat = p.tbKKXQ.colLat,
                                                                   Lon = p.tbKKXQ.colLon}
                                       into g
                                       select g).ToList().Select(m => new MeasureLocationModel()
                                           {
                                               Id = m.Key.Id,
                                               Name = m.Key.Kyhieu,
                                               Position = m.Key.Vitri,
                                               Lat = m.Key.Lat,
                                               Lon = m.Key.Lon,
                                               SampleId = m.Distinct().Aggregate("", (current, tbKkxqMau) => current + (tbKkxqMau.ID + " ")).Trim()
                                           }).ToList();

            model.ReportModel.Materials = (from p in DaoBase.Data.tbKKXQ_Mau_KQ
                                           group p.tbKKXQ by p.tbParam into g
                                           select g).ToList().Select(m =>
                                               new StaticMaterialModel()
                                                   {
                                                       Id =  m.Key.ID,
                                                       Name = m.Key.colName,
                                                       Unit = m.Key.colUnits,
                                                       Formula = m.Key.colEquation,
                                                       Status = m.Key.tbParamType.colName,
                                                       AreaId = m.Distinct().Aggregate("", (result, item) => result + item.ID + " ").Trim()
                                                   }).ToList();
            return model;
        }

        /// <summary>
        /// Get data for popup model
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mappedTable"></param>
        /// <returns></returns>
        private PopupModel GetModel(int? id, string mappedTable)
        {
            //Check if the selected object is "tbDat"
            if (mappedTable == "tbDat")
            {
                var entity = DaoBase.Data.tbDats.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbDat>();
                var lastestPattern = DaoBase.Data.tbDat_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbDat_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                                  {
                                      TenChat = m.tbParam.colName,
                                      DonVi = m.tbParam.colUnits,
                                      GiaTriDo = m.colGTriDouble,
                                      Qcvn = m.tbParam.GetQcvn()
                                  }).ToList();

                return new PopupModel
                    {
                        Header = template.GetHeader(this),
                        Info = template.GetInfo(this, entity),
                        InfoTable = template.GetInfoTable(this, entity, source),
                        InfoChart = template.GetInfoChart(this, entity, source)
                    };
            }

            //Check if the selected object is "tbNuocho"
            if (mappedTable == "tbNuocho")
            {
                var entity = DaoBase.Data.tbNuochoes.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbNuocho>();
                var lastestPattern = DaoBase.Data.tbDat_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbNuocho_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbNuocsong"
            if (mappedTable == "tbNuocsong")
            {
                var entity = DaoBase.Data.tbNuocsongs.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbNuocsong>();
                var lastestPattern = DaoBase.Data.tbNuocsong_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbNuocsong_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbKkxq"
            if (mappedTable == "tbKkxq")
            {
                var entity = DaoBase.Data.tbKKXQs.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbKKXQ>();
                var lastestPattern = DaoBase.Data.tbKKXQ_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbKKXQ_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbNuocbien"
            if (mappedTable == "tbNuocbien")
            {
                var entity = DaoBase.Data.tbNuocbiens.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbNuocbien>();
                var lastestPattern = DaoBase.Data.tbNuocbien_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbNuocbien_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbTramtich"
            if (mappedTable == "tbTramtich")
            {
                var entity = DaoBase.Data.tbTramtiches.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbTramtich>();
                var lastestPattern = DaoBase.Data.tbTramtich_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbTramtich_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbMothuysan"
            if (mappedTable == "tbMothuysan")
            {
                var entity = DaoBase.Data.tbMothuysans.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbMothuysan>();
                var lastestPattern = DaoBase.Data.tbMothuysan_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbMothuysan_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            //Check if the selected object is "tbNuocho"
            if (mappedTable == "tbNuocngam")
            {
                var entity = DaoBase.Data.tbNuocngams.SingleOrDefault(e => e.ID == id);
                var template = new BasePopupTemplate<tbNuocngam>();
                var lastestPattern = DaoBase.Data.tbNuocngam_Mau.Max(m => m.ID);
                var source = (from p in DaoBase.Data.tbNuocngam_Mau_KQ
                              where p.colSrcID == id && p.colMauID == lastestPattern
                              select p).ToList().Select(m => new RowPopupModel
                              {
                                  TenChat = m.tbParam.colName,
                                  DonVi = m.tbParam.colUnits,
                                  GiaTriDo = m.colGTriDouble,
                                  Qcvn = m.tbParam.GetQcvn()
                              }).ToList();

                return new PopupModel
                {
                    Header = template.GetHeader(this),
                    Info = template.GetInfo(this, entity),
                    InfoTable = template.GetInfoTable(this, entity, source),
                    InfoChart = template.GetInfoChart(this, entity, source)
                };
            }

            return null;
        }
        
        #endregion
    }
}
